package models;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.tom.basic.utils.XTimeUtils;
import models.base.BaseModel;
import org.apache.commons.lang.StringUtils;

import javax.persistence.Entity;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Entity
public class UserTDTiMu extends BaseModel {

    public Long bigCateId;

    public String qaIds;

    public String tdDate;

    public String openId;

    public static void init(String openId, Long bigCateId) {
        if (StringUtils.isEmpty(openId) || bigCateId == null) {
            return;
        }
        String date = XTimeUtils.formatDate(new Date(), "yyyy-MM-dd");
        UserTDTiMu tdTiMu = UserTDTiMu.find("openId=:openId and isDelete = 0 and tdDate=:tdDate and bigCateId=:bigCateId")
                .setParameter("bigCateId", bigCateId)
                .setParameter("tdDate", date).setParameter("openId", openId).first();
        if (tdTiMu != null) {
            return;
        }
        tdTiMu = new UserTDTiMu();
        tdTiMu.openId = openId;
        tdTiMu.tdDate = date;
        tdTiMu.bigCateId = bigCateId;
        List<QuestionAnswer> answerList = QuestionAnswer.find("isDelete = 0 and bigCateId=:bigCateId order by id desc ").setParameter(
                "bigCateId", bigCateId).fetch(2000);
        Collections.shuffle(answerList);
        answerList = answerList.subList(0, Math.min(answerList.size(), 100));
        tdTiMu.qaIds = Joiner.on(",").join(answerList.stream().map(e -> e.id).collect(Collectors.toList()));
        tdTiMu.save();
    }


    public static List<QuestionAnswer> getQaIds(String openId, Long bigCateId) {
        String date = XTimeUtils.formatDate(new Date(), "yyyy-MM-dd");
        UserTDTiMu tdTiMu = UserTDTiMu.find("openId=:openId and isDelete = 0 and tdDate=:tdDate and bigCateId=:bigCateId")
                .setParameter("bigCateId", bigCateId)
                .setParameter("tdDate", date).setParameter("openId", openId).first();
        if (tdTiMu == null || StringUtils.isEmpty(tdTiMu.qaIds)) {
            init(openId, bigCateId);
            return Lists.newArrayList();
        }
        List<Long> qaIds = Splitter.on(",").splitToList(tdTiMu.qaIds).stream().map(e -> Long.parseLong(e)).collect(Collectors.toList());
        List<QuestionAnswer> answers = QuestionAnswer.find("isDelete = 0  and id in(:ids)").setParameter("ids", qaIds).fetch();
        Map<Long, QuestionAnswer> answerMap = answers.stream().collect(Collectors.toMap(e -> e.id, e -> e));
        List<QuestionAnswer> result = Lists.newArrayList();
        qaIds.forEach(e -> {
            QuestionAnswer answer = answerMap.get(e);
            if (answer != null) {
                result.add(answer);
            }
        });
        return result;
    }

}
